package com.redsoft.spirit.realm;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import com.redsoft.spirit.entity.StatelessToken;

public class StatelessRealm extends AuthorizingRealm {
	public boolean supports(AuthenticationToken token) {
		return token instanceof StatelessToken;
	}

	/**
	 * 
	 * 授权.
	 * <pre>
	 * 	这块可以根据登录的用户身份进行查找这个人的所有权限，比如roles, permissions
	 * </pre>
	 * 
	 * @see org.apache.shiro.realm.AuthorizingRealm#doGetAuthorizationInfo(org.apache.shiro.subject.PrincipalCollection)
	 */
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		String username = (String) principals.getPrimaryPrincipal();
		SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
		authorizationInfo.addRole("admin");
		
		return authorizationInfo;
	}

	/**
	 * 
	 * 此处的身份认证方法实质上已经没有啥意义，强制通过了.
	 * <pre>
	 * 	因为使用了jwt，所以这块就不想再做二次认证了
	 * </pre>
	 * 
	 * @see org.apache.shiro.realm.AuthenticatingRealm#doGetAuthenticationInfo(org.apache.shiro.authc.AuthenticationToken)
	 */
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		StatelessToken statelessToken = (StatelessToken) token;
		String username = statelessToken.getUsername();

		String serverDigest = "admin";

		System.out.println("客户端的摘要" + statelessToken.getClientDigest());
		System.out.println("服务器端摘要" + serverDigest);

		return new SimpleAuthenticationInfo(username, serverDigest, getName());
	}
}